package lq.auth.studyauth.translator;

import lombok.extern.slf4j.Slf4j;
import lq.common.entity.StudyResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

/**
 * @program: cloud-study
 * @description: 权限认证异常翻译器
 * @Slf4j用于往当前类中注入org.slf4j.Logger日志打印对象，效果相当于在类里定义如下属性：
 * private Logger log = LoggerFactory.getLogger(this.getClass());
 * @author: LQ
 * @create: 2020-09-29 14:26
 */
@Slf4j
@Component
public class StudyWebResponseExceptionTranslator implements WebResponseExceptionTranslator {
    @Override
    public ResponseEntity translate(Exception e) throws Exception {
        // 统一返回500HTTP状态码（HttpStatus.INTERNAL_SERVER_ERROR）
        ResponseEntity.BodyBuilder status = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR);
        StudyResponse response = new StudyResponse();
        String message = "认证失败";
        log.error(message,e);
        if (e instanceof UnsupportedGrantTypeException){
            message = "不支持该认证类型";
            return status.body(response.message(message));
        }
        if (e instanceof InvalidGrantException){
            if (StringUtils.containsIgnoreCase(e.getMessage(),"Invalid refresh token")){
                message = "refresh token无效";
                return status.body(response.message(message));
            }
            if (StringUtils.containsIgnoreCase(e.getMessage(), "locked")) {
                message = "用户已被锁定，请联系管理员";
                return status.body(response.message(message));
            }
            message = "用户名或密码错误";
            return status.body(response.message(message));
        }
        return status.body(response.message(message));
    }
}
